﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace COSL_Initial
{
    public static class Utilities
    {
        public static SPList EnsureList(this SPWeb web, string listTitle, string desc, SPListTemplateType lstTemplateType)
        {
            SPListCollection lstCollection = web.Lists;
            SPList lstObj = (from SPList lst in lstCollection
                             where string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                             select lst).FirstOrDefault();

            if (lstObj != null)
            {
                return lstObj;
            }

            Guid lstGuid = web.Lists.Add(listTitle, desc, lstTemplateType);
            try
            {
                SPList newList = web.Lists.GetList(lstGuid, true);
                newList.OnQuickLaunch = true;
                newList.Update();
                return newList;
            }
            catch
            {
                return null;
            }
        }

        public static SPField EnsureField(this SPList list, string fldDisplayName, string fldDesc, SPFieldType fldType, bool isMadatory)
        {
            SPFieldCollection fieldCollection = list.Fields;
            SPField spField = (from SPField field in fieldCollection
                               where string.Equals(field.Title, fldDisplayName, StringComparison.InvariantCultureIgnoreCase) == true
                               select field).FirstOrDefault();

            if (spField != null)
            {
                return spField;
            }
            try
            {
                list.Fields.Add(fldDisplayName, fldType, isMadatory);
                SPField spfield = list.Fields.GetField(fldDisplayName);
                spfield.Description = fldDesc;
                spfield.Update();
                return spfield;
            }
            catch
            {
                return null;
            }
        }

        public static bool DeleteList(this SPWeb web, string listTitle)
        {
            SPListCollection lstCollection = web.Lists;
            SPList lstObj = (from SPList lst in lstCollection
                             where
                                 string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                             select lst).FirstOrDefault();

            if (lstObj != null)
            {
                try
                {
                    lstObj.Delete();
                    return true;
                }
                catch (Exception ex)
                {
                }
            }
            return false;
        }
    }
}
